package com.heima.article.listen;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.mess.UpdateArticleMess;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author lo
 * @date 2021/10/8
 */
@Slf4j
@Component
public class HotArticleScoreListener {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queuesToDeclare = @Queue(value = HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE))
    public void articleBehaviorHandler(@Payload String articleMess, Message message, Channel channel) {
        log.debug("接收到用户行为操作,开始处理用户行为信息 当前时间: {}", LocalDateTime.now().toString());
        try {
            //1.将数据存入redis中
            ListOperations<String, String> listOperations = redisTemplate.opsForList();
            listOperations.rightPush(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST, articleMess);

            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            log.info(" 文章实时更新队列: 接收到文章行为变化 消息内容: {" +
                    "}",articleMess);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文章实时更新队列， 消息处理失败: {}   失败原因: {}",articleMess,e.getMessage());
        }
    }
}
